package com.hh.shirojwt.controller;

import com.hh.shirojwt.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;


    @GetMapping(value = "/login")
    public String defaultLogin() {
        return "登录页";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletResponse response){

        if(StringUtils.isEmpty( username ) || StringUtils.isEmpty( password )){
            return "用户账号密码为空";
        }

        //servise mkt 验证
        boolean isOk = loginService.login(username, password);
        if(!isOk){
            return "登录验证失败";
        }

        //生成用户token，有效时间8小时
        String jwtToken = loginService.creatJwtTokne(username);
        //写入header
        response.setHeader("Authorization", jwtToken);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return jwtToken;
    }

    @GetMapping("/getIndex")
    public String getIndex(){
        return "首页";
    }


}
